package com.wiim.interfaceapp;


import com.wiim.handler.BaseCmdHandler;
import com.wiim.nhapnhap.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;

public class CommandAsyncTask extends AsyncTask<Void, Void, Void> {
	IServiceCommandResult host = null;
	int commandCode = 0;
	Bundle resultData;
	Bundle cmdData;
	BaseCmdHandler cmdHandler;
	AlertDialog progressDialog = null;
	boolean showProgress = true;

	public CommandAsyncTask(IServiceCommandResult host, BaseCmdHandler handler,
			int command, Bundle data) {
		this.host = host;
		this.commandCode = command;
		this.cmdData = data;
		this.cmdHandler = handler;
	}

	public CommandAsyncTask(Object ac2, BaseCmdHandler handler,
			int command, Bundle data, boolean progress) {
		this.host = (IServiceCommandResult) ac2;
		this.commandCode = command;
		this.cmdData = data;
		this.cmdHandler = handler;
		this.showProgress = progress;
	}

	@Override
	protected Void doInBackground(Void... arg0) {
		resultData = cmdHandler.commandHandler(commandCode, cmdData);
		return null;
	}

	@Override
	protected void onPostExecute(Void unused) {
		if (progressDialog != null) {
			progressDialog.dismiss();
		}

		host.processCommandResult(commandCode, resultData);
	}

	@Override
	protected void onPreExecute() {
		if (!showProgress) {
			return;
		}

		Activity context = null;
		if (this.host instanceof Activity) {
			context = (Activity) host;

			AlertDialog.Builder builder = new AlertDialog.Builder(
					context.getParent() == null ? context : context.getParent());
			View progressView = LayoutInflater
					.from(context.getParent() == null ? context : context
							.getParent()).inflate(
							R.layout.screen_progress_dialog, null);
//			progressView.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
			builder.setView(progressView);			
			progressDialog = builder.create();
			progressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			progressDialog.show();

		}

	}

}
